from typing import List

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from database.manager import DbManager
from database.models import Tour as TourModel
from database.schemas.tour import TourResponse, TourCreate
from security import check_token

router = APIRouter()

db_manager = DbManager()


@router.get("/", response_model=List[TourResponse])
def get_tours(db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    tours = db.query(TourModel).all()
    return tours


@router.get("/{tour_id}", response_model=TourResponse)
def get_tour(tour_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    tour = db.query(TourModel).filter(TourModel.id == tour_id).first()
    if tour is None:
        raise HTTPException(status_code=404, detail="Tour not found")
    return tour


@router.post("/", response_model=TourResponse)
def add_tour(tour: TourCreate, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    db_tour = TourModel(**tour.dict())
    db.add(db_tour)
    db.commit()
    db.refresh(db_tour)
    return db_tour


@router.delete("/{tour_id}", response_model=TourResponse)
def delete_tour(tour_id: int, db: Session = Depends(db_manager.get_session), token: str = Depends(check_token)):
    tour = db.query(TourModel).filter(TourModel.id == tour_id).first()
    if tour is None:
        raise HTTPException(status_code=404, detail="Tour not found")
    db.delete(tour)
    db.commit()
    return {"detail": "Tour deleted"}


@router.put("/{tour_id}", response_model=TourResponse)
def edit_tour(tour_id: int, tour: TourCreate, db: Session = Depends(db_manager.get_session),
              token: str = Depends(check_token)):
    db_tour = db.query(TourModel).filter(TourModel.id == tour_id).first()
    if db_tour is None:
        raise HTTPException(status_code=404, detail="Tour not found")
    db_tour.name = tour.name
    db_tour.description = tour.description
    db_tour.price = tour.price
    db_tour.photo = tour.photo
    db_tour.duration = tour.duration
    db.commit()
    db.refresh(db_tour)
    return db_tour
